<template>
    <div class="upload-container">
        <div>
            <input type="file" @change="onFileSelected" />
            <button @click="uploadFile">上传文件</button>
        </div>
        <div>
            <button @click="exportFile">导出文件</button>
        </div>
    </div>
</template>

<script>
import axios from "axios";
import SparkMD5 from 'spark-md5';

export default {
    data() {
        return {
            chunkSize: 1024 * 1024, // 1MB 分片大小
            file: null, // 选择的文件对象
            fileId: null, // 文件的md5
            totalChunks: 0, // 文件分片总数
            chunkIndex: 0, // 当前分片索引
        };
    },
    methods: {
        calculateMD5() {
            if (!this.file) return;
            const reader = new FileReader();
            reader.onload = (event) => {
                const buffer = event.target.result;
                const spark = new SparkMD5.ArrayBuffer();
                spark.append(buffer);
                const md5 = spark.end();
                this.fileId = md5;
                console.log("MD5:", md5);
            };
            reader.readAsArrayBuffer(this.file);
        },
        onFileSelected(event) {
            this.file = event.target.files[0];
            this.totalChunks = Math.ceil(this.file.size / this.chunkSize);
            // 计算出文件的md5
            this.calculateMD5();
        },
        uploadFile() {
            console.log("开始上传文件！");
            if (!this.file) return;
            if (!this.fileId) {
                alert("正在加载请稍后！");
                return;
            }
            this.uploadNextChunk();
        },
        uploadNextChunk() {
            if (this.chunkIndex >= this.totalChunks) return;

            const start = this.chunkIndex * this.chunkSize;
            const end = Math.min(start + this.chunkSize, this.file.size);
            const chunk = this.file.slice(start, end);
            // 获取文件的拓展名
            const extension = this.file.name.split(".").pop();
            // 创建FormData对象
            const formData = new FormData();
            formData.append("file", chunk);
            formData.append("chunkIndex", this.chunkIndex);
            formData.append("totalChunks", this.totalChunks);
            formData.append("fileId", this.fileId);
            formData.append("extension", extension);

            axios
                .post("http://127.0.0.1:8080/file/excel/upload", formData, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                })
                .then((response) => {
                    // console.log(response);
                    if (response.data.code == 200) {
                        if (this.chunkIndex == this.totalChunks - 1) {
                            console.log("文件上传成功！");
                        } else {
                            this.chunkIndex++;
                            this.uploadNextChunk();
                        }
                    }
                    else {
                        if (response.data.msg == "文件已存在") {
                            alert("文件已存在，请勿重复上传！");
                            return;
                        }
                        if (response.data.msg == "分片索引不一致") {
                            this.chunkIndex = response.data.data;
                            this.uploadNextChunk();
                        }
                    }

                })
                .catch((error) => console.error("上传错误：", error));
        },
        initWebSocket() {
            const socket = new WebSocket("ws://127.0.0.1:8080/websocket");
            // 监听WebSocket的连接状态变化
            socket.onopen = function (event) {
                console.log('WebSocket连接已打开');
            };

            // 监听从服务器发送过来的消息
            socket.onmessage = function (event) {
                console.log('从服务器接收到消息:', event.data);
            };

            // 监听WebSocket连接关闭
            socket.onclose = function (event) {
                console.log('WebSocket连接已关闭');
            };

            // 监听WebSocket错误
            socket.onerror = function (error) {
                console.error('WebSocket发生错误:', error);
            };
        },
        exportFile(){
            axios.get("http://127.0.0.1:8080/export/excel")
            .then((response) => {
                console.log(response.data);
            });
        }
    },
    mounted() {
        
    },
    created() {
        this.initWebSocket();
    },
};
</script>

<style scoped>
.upload-container {
    background-color: bisque;
}
</style>
